package com.momoc.netty.frame;

import com.google.protobuf.MessageLiteOrBuilder;
import com.momoc.netty.frame.dispatch.model.PacketMassageInfo;
import com.momoc.netty.frame.handler.ProtobufDecoder;
import com.momoc.netty.frame.handler.ProtobufEnCoderHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * @author momoc
 * @version 1.0
 * @className ProtobufUtils
 * @description
 * @date 2024/5/28 11:38
 */
public class ProtobufUtils {



    static ProtobufEnCoderHandler protobufEnCoderHandler = new ProtobufEnCoderHandler();
    /**
     * 对入站消息进行解码
     *
     * @param message 二进制
     * @return
     */
    public static MessageLiteOrBuilder decodeRequestMessage(byte[] message)  {
        ByteBuf byteBuf = Unpooled.wrappedBuffer(message);
        PacketMassageInfo messageInfo = ProtobufDecoder.getRequestMessageInfo(byteBuf);
        ProtobufDecoder protobufDecoder = messageInfo.getProtobufDecoder();
        return protobufDecoder.decode(byteBuf);
    }


    /**
     * 对出站消息进行编码
     * @param messageLiteOrBuilder 消息
     * @return
     */
    public static ByteBuf encodeResponseMessage(MessageLiteOrBuilder messageLiteOrBuilder) {
        return protobufEnCoderHandler.encode(messageLiteOrBuilder);
    }


    /**
     * 用于解将出站二进制信息的重新序列化为对象
     * @param bytes 二进制
     * @return
     */
    public static MessageLiteOrBuilder decodeResponseMessage(byte[] bytes) {

        ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes);
        PacketMassageInfo responseMessageInfo = ProtobufEnCoderHandler.getResponseMessageInfo(byteBuf);
        ProtobufDecoder protobufDecoder = responseMessageInfo.getProtobufDecoder();
        return protobufDecoder.decode(byteBuf);
    }

}
